package com.sj.common.exception;

import com.sj.common.utils.ThrowableUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.CannotCreateTransactionException;

@Aspect
@Component
/**
 * @description: bo异常拦截器
 */
public class MbsExceptionAspect {
    private Logger logger = LoggerFactory.getLogger(MbsExceptionAspect.class);

    @Pointcut("execution(* com.sj.mbs..*ServiceImpl.*(..))")
    public void pointCut() {
        //切面
    }

    /**
     * @description: 切点异常退出的统一处理方法
     * @param: [jp 切点对象, ex 异常]
     */
    @AfterThrowing(throwing = "ex", pointcut = "pointCut()")
    public void afterThrowing(JoinPoint jp, Throwable ex) throws Exception {
        Class<?> cls = null;
        Object fieldValue = null;
        // 获取bo中的类别名，以便在提示信息中展示
        try {
            cls = jp.getTarget().getClass();
            fieldValue = cls.getField("CLASS_ALIAS").get(cls);
        } catch (Exception e) {
            if (cls == null) {
                throw new MbsException(240010, "无法获取抛出异常的信息");
            } else {
                fieldValue = cls.getName();
            }
        }


        if (ex instanceof MbsException) {
            //如果是MbsException则不用处理
        } else if (ex instanceof DuplicateKeyException) {
            throw new MbsException(240012, "数据库错误：请勿插入重复的主键！"+ex.getMessage()+"" + ThrowableUtil.getErrorNo((String) fieldValue));
        } else if (ex instanceof DataIntegrityViolationException) {
            String msg = "数据库错误：新增或修改数据时违反了完整性"+ex.getMessage()+"！";
            logger.error(msg, ex);
            throw new MbsException(240013, msg + ThrowableUtil.getErrorNo((String) fieldValue));
        } else if (ex instanceof CannotCreateTransactionException) {
            String msg = "无法打开事务的JDBC连接"+ex.getMessage()+"";
            logger.error(msg, ex);
            throw new MbsException(240014, msg + ThrowableUtil.getErrorNo((String) fieldValue));
        } else {
            logger.error("系统错误：", ex);
            String message = ex.getMessage();
            //所有其他异常
            throw new MbsException(240011, "系统错误：" + message + ThrowableUtil.getErrorNo((String) fieldValue));
        }
    }
}
